package com.neusoft.nepg.service.imp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.neusoft.common.domain.Grider;
import com.neusoft.interceptor.JWTUtil;
import com.neusoft.nepg.mapper.GriderMapper;
import com.neusoft.nepg.service.GriderService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class GriderServiceImp extends ServiceImpl<GriderMapper, Grider> implements GriderService {
    @Resource
    private GriderMapper griderMapper;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private static final Logger log = LoggerFactory.getLogger(GriderServiceImp.class);
    @Override
    public List<Grider> queryList(int id,int cid) {
        return griderMapper.areaList(id, cid);
    }

    @Override
    public Map<String, Object> login(Grider grider) {
        Map<String,Object> result = new HashMap<>();
        try {
            Map<String,Object> test = new HashMap<>();
            test.put("admin_code",grider.getAdmin_code());
            test.put("password",grider.getPassword());
            Grider get = griderMapper.selectByMap(test).size()==0?null:griderMapper.selectByMap(test).get(0);
            System.out.println(get);
            if (get!=null){
                Map<String, String> payload = new HashMap<>();
                //封装payload,这里面放需要前台未来用来验证的信息
                payload.put("adminCode", String.valueOf(get.getAdmin_code()));
                payload.put("name", get.getName());
                payload.put("password", get.getPassword());
                // 生成token
                String token= JWTUtil.getToken(payload);
                result.put("status", true);
                result.put("msg", "登录成功");
                result.put("token", token); // 响应token，存储在客户端
                //存储todo....redis
                redisTemplate.opsForValue().set(get.getAdmin_code(), token, 30, TimeUnit.MINUTES);
            }else {
                log.info("编码或密码有误");
                result.put("status", false);
                result.put("msg", "编码或密码有误");
            }
        }catch (Exception e){
            log.info("登录失败...");
            result.put("status", false);
            result.put("msg", "登录失败");
        }
        return result;
    }

    @Override
    public Grider findGrider(String code) {
        List<Grider> list = griderMapper.findGrider(code);
        if (list.size()!=0){
            return list.get(0);
        }else return null;

    }
}
